<template>
    <div class="settings-view">
        <h1 class="view-title">设置</h1>

        <div class="settings-grid">
            <!-- 用户信息 -->
            <div class="settings-card" id="user-info-card">
                <!-- ... 用户信息卡片内容保持不变 ... -->
                <h2 class="card-title">用户信息</h2>
                <div class="avatar-section">
                    <el-avatar
                        :size="80"
                        :src="userStore.user?.avatar || defaultAvatar"
                        @error="() => true"
                        @click="editAvatar" 
                        class="clickable-avatar"
                        title="点击修改头像" 
                    >
                         <img :src="defaultAvatar" />
                     </el-avatar>
                </div>
                <div class="settings-list">
                     <div class="setting-item">
                        <span class="item-label">用户名</span>
                        <div class="item-control">
                             <el-input v-model="editableUserInfo.username" size="small" placeholder="输入用户名" class="inline-input"/>
                        </div>
                    </div>
                     <div class="setting-item">
                        <span class="item-label">身份</span>
                        <div class="item-control">
                             <span class="item-value">{{ displayRole }}</span>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">邮箱</span>
                        <div class="item-control">
                             <el-input v-model="editableUserInfo.email" size="small" placeholder="输入邮箱" class="inline-input"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">昵称</span>
                        <div class="item-control">
                            <el-input v-model="editableUserInfo.nickname" size="small" placeholder="输入昵称" class="inline-input"/>
                        </div>
                    </div>
                </div>
                <div class="user-info-actions">
                    <el-button type="primary" size="small" @click="saveUserProfile">保存用户信息</el-button>
                </div>
            </div>

            <!-- 账号设置 -->
            <div class="settings-card">
                <h2 class="card-title">账号设置</h2>
                <div class="settings-list">
                    <div class="setting-item">
                        <span class="item-label">位置名称</span>
                        <div class="item-control">
                            <el-input v-model="editableLocationName" size="small" placeholder="当前位置名称" style="width: 180px;" :disabled="!isEditingLocation"/>
                            <el-button type="primary" size="small" v-if="!isEditingLocation && isAdmin" @click="startEditLocation" class="location-edit-btn">
                                <el-icon><Edit /></el-icon>
                            </el-button>
                            <el-button type="primary" size="small" v-else-if="isEditingLocation" @click="updateLocationName" class="location-edit-btn">
                                保存
                            </el-button>
                            <el-button v-if="isEditingLocation" size="small" @click="cancelEditLocation" class="location-edit-btn">
                                取消
                            </el-button>
                        </div>
                    </div>

                    <div class="setting-item clickable" @click="navigateTo('修改密码')">
                        <span class="item-label">修改密码</span>
                        <div class="item-control">
                        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                        </div>
                    </div>
                    <div class="setting-item clickable" @click="navigateTo('隐私设置')">
                        <span class="item-label">隐私设置</span>
                        <div class="item-control">
                        <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                        </div>
                    </div>
                    <div class="setting-item logout-item clickable" @click="logout">
                        <span class="item-label logout-label">退出登录</span>
                        <div class="item-control">
                        <el-icon class="logout-icon"><SwitchButton /></el-icon>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统设置 -->
            <div class="settings-card">
                <h2 class="card-title">系统设置</h2>
                <div class="settings-list">
                    <div class="setting-item">
                        <span class="item-label">语言设置</span>
                        <div class="item-control">
                        <el-select v-model="settings.language" placeholder="选择语言" size="small" style="width: 120px;">
                            <el-option
                                v-for="item in languageOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">系统名称</span>
                        <div class="item-control">
                        <el-input v-model="settings.systemName" size="small" placeholder="系统名称" style="width: 150px; text-align: right;"/>
                    </div>
                    </div>
                    <!-- 从通知设置移动过来的选项 -->
                    <div class="setting-item">
                        <span class="item-label">物品过期提醒</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.expiration"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">库存预警</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.lowStock"/>
                        </div>
                    </div>
                    <div class="setting-item">
                        <span class="item-label">数据更新提醒</span>
                        <div class="item-control">
                        <el-switch v-model="settings.notifications.updates"/>
                    </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="settings-actions">
            <el-button @click="resetSettings">重置系统设置</el-button>
            <el-button type="primary" @click="saveSettings">保存系统设置</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue';
import { ElMessage, ElAvatar, ElInput } from 'element-plus';
import { ArrowRight, Moon, Sunny, CircleCheck, Warning, Bell, SwitchButton, Edit } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { usePermissionStore } from '@/stores/permission';
import { locationsApi } from '@/utils/apiService';

const router = useRouter();
const userStore = useUserStore();
const permissionStore = usePermissionStore();

const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');

// Reactive state for editable user info
const editableUserInfo = reactive({
    username: '',
    email: '',
    nickname: '',
});

// Watch for changes in userStore.user to initialize/update editableUserInfo
watch(() => userStore.user, (newUser) => {
    if (newUser) {
        editableUserInfo.username = newUser.username || '';
        editableUserInfo.email = newUser.email || '';
        editableUserInfo.nickname = newUser.nickname || '';
    }
}, { immediate: true, deep: true }); // immediate to run on mount, deep if user is nested

const isDarkMode = ref(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);

const settings = reactive({
                systemName: '家居物品管理系统',
    theme: 'auto',
                iCloudSync: true,
                notifications: {
                    expiration: true,
                    lowStock: true,
                    updates: false
    },
    language: 'zh-CN',
    password: '',
    privacyLevel: 'standard',
});

let originalSettings = {};

const languageOptions = [
    { value: 'zh-CN', label: '简体中文' },
    { value: 'en-US', label: 'English' },
];

const displayRole = computed(() => {
  const roleId = userStore.user?.roleId;
  switch (roleId) {
    case 1: return '管理员';
    case 2: return '管理者';
    case 3: return '成员';
    case 0: return '访客';
    default: return userStore.user?.roleName || '未知';
  }
});

const updateTheme = () => {
    if (settings.theme === 'auto') {
        isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
            } else {
        isDarkMode.value = settings.theme === 'dark';
            }
    document.documentElement.classList.toggle('dark', isDarkMode.value);
};

const handleSystemThemeChange = (e) => {
    if (settings.theme === 'auto') {
        isDarkMode.value = e.matches;
        document.documentElement.classList.toggle('dark', isDarkMode.value);
    }
};

watch(() => settings.theme, updateTheme);
            
// 新增：判断当前用户是否为管理员
const isAdmin = computed(() => {
  // 获取当前位置ID
  const locationId = selectedLocationId.value || localStorage.getItem('currentLocationId');
  if (!locationId) return false;
  
  // 检查用户在该位置的角色
  return permissionStore.canManageLocationUsers(locationId);
});

// 位置相关数据
const userLocations = ref([]);
const selectedLocationId = ref(null);
const editableLocationName = ref('');
const locationLoading = ref(false);
const isEditingLocation = ref(false);
const originalLocationName = ref('');

// 获取用户所有位置
const fetchUserLocations = async () => {
    try {
        locationLoading.value = true;
        // 获取当前用户ID
        const userId = userStore.user?.id;
        if (!userId) {
            console.error('未找到用户ID，无法获取位置信息');
            return;
        }

        const response = await locationsApi.getUserLocations(userId);
        if (response && response.code === 200 && response.data) {
            userLocations.value = response.data;
            
            // 如果有位置，默认选中当前位置或第一个
            if (userLocations.value.length > 0) {
                // 尝试从路由或localStorage获取当前位置ID
                const currentLocationId = router.currentRoute.value.query?.locationId || 
                                        localStorage.getItem('currentLocationId');
                
                if (currentLocationId) {
                    // 检查当前位置ID是否在用户位置列表中
                    const exists = userLocations.value.some(location => location.id == currentLocationId);
                    if (exists) {
                        selectedLocationId.value = currentLocationId;
                        const location = userLocations.value.find(loc => loc.id == currentLocationId);
                        if (location) {
                            editableLocationName.value = location.name;
                        }
                    } else {
                        // 如果不存在，选择第一个
                        selectedLocationId.value = userLocations.value[0].id;
                        editableLocationName.value = userLocations.value[0].name;
                    }
                } else {
                    // 没有当前位置ID，选择第一个
                    selectedLocationId.value = userLocations.value[0].id;
                    editableLocationName.value = userLocations.value[0].name;
                }
            }
        }
    } catch (error) {
        console.error('获取用户位置出错:', error);
        ElMessage.error('获取位置信息失败');
    } finally {
        locationLoading.value = false;
    }
};

// 开始编辑位置名称
const startEditLocation = () => {
    // 检查权限
    if (!isAdmin.value) {
        ElMessage.error('权限不足，只有管理员可以修改位置名称');
        return;
    }
    
    originalLocationName.value = editableLocationName.value;
    isEditingLocation.value = true;
};

// 取消编辑位置名称
const cancelEditLocation = () => {
    editableLocationName.value = originalLocationName.value;
    isEditingLocation.value = false;
};

// 更新位置名称
const updateLocationName = async () => {
    // 再次检查权限
    if (!isAdmin.value) {
        ElMessage.error('权限不足，只有管理员可以修改位置名称');
        isEditingLocation.value = false;
        editableLocationName.value = originalLocationName.value;
        return;
    }

    if (!selectedLocationId.value) {
        ElMessage.warning('未找到当前位置');
        isEditingLocation.value = false;
        return;
    }

    if (!editableLocationName.value.trim()) {
        ElMessage.warning('位置名称不能为空');
        return;
    }

    if (editableLocationName.value === originalLocationName.value) {
        isEditingLocation.value = false;
        return;
    }

    try {
        locationLoading.value = true;

        const response = await locationsApi.updateLocation(
            selectedLocationId.value, 
            { name: editableLocationName.value.trim() }
        );

        if (response && response.code === 200) {
            ElMessage.success('位置名称更新成功');
            isEditingLocation.value = false;
            
            // 刷新位置列表
            await fetchUserLocations();
            
            // 设置标记以便在返回时刷新Dashboard
            if (router.currentRoute && router.currentRoute.value) {
                router.currentRoute.value.meta.fromSettings = true;
            }
            
            // 更新localStorage中的位置名称
            try {
                // 刷新当前位置显示
                const updatedLocations = JSON.parse(localStorage.getItem('userLocations') || '[]');
                const locationIndex = updatedLocations.findIndex(loc => loc.id === selectedLocationId.value);
                
                if (locationIndex !== -1) {
                    updatedLocations[locationIndex].name = editableLocationName.value.trim();
                    localStorage.setItem('userLocations', JSON.stringify(updatedLocations));
                }
            } catch (error) {
                console.error('更新localStorage中的位置名称失败:', error);
            }
        } else {
            ElMessage.error(response?.msg || '更新位置名称失败');
        }
    } catch (error) {
        console.error('更新位置名称出错:', error);
        ElMessage.error('更新位置名称失败');
    } finally {
        locationLoading.value = false;
    }
};

onMounted(() => {
    originalSettings = JSON.parse(JSON.stringify(settings));
    loadSettings();
    updateTheme();
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', handleSystemThemeChange);
    if (!userStore.user) {
        userStore.getCurrentUser();
    }
    // Initialize editableUserInfo if user is already available
    if (userStore.user) {
         editableUserInfo.username = userStore.user.username || '';
         editableUserInfo.email = userStore.user.email || '';
         editableUserInfo.nickname = userStore.user.nickname || '';
    }
    
    // 获取用户位置
    fetchUserLocations();
});

onUnmounted(() => {
    window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', handleSystemThemeChange);
});

const loadSettings = () => {
    console.log('加载设置...');
    const savedSettings = localStorage.getItem('appSettings');
    if (savedSettings) {
        const parsedSettings = JSON.parse(savedSettings);
        const validKeys = Object.keys(settings);
        for (const key of validKeys) {
            if (parsedSettings.hasOwnProperty(key)) {
                 if (key === 'notifications' && typeof parsedSettings[key] === 'object') {
                    Object.assign(settings.notifications, parsedSettings.notifications);
                 } else {
                    settings[key] = parsedSettings[key];
                 }
            }
        }
    }
    originalSettings = JSON.parse(JSON.stringify(settings));
};

const saveSettings = () => {
    console.log('保存设置:', JSON.parse(JSON.stringify(settings)));
    localStorage.setItem('appSettings', JSON.stringify(settings));
    ElMessage.success('设置已保存');
    originalSettings = JSON.parse(JSON.stringify(settings));
};

const resetSettings = () => {
    const defaultSettings = {
        systemName: '家居物品管理系统',
        theme: 'auto',
        iCloudSync: true,
        notifications: {
            expiration: true,
            lowStock: true,
            updates: false
        },
        language: 'zh-CN',
        password: '',
        privacyLevel: 'standard',
    };
    Object.assign(settings, JSON.parse(JSON.stringify(defaultSettings)));
    updateTheme();
    ElMessage.info('设置已重置');
    localStorage.setItem('appSettings', JSON.stringify(settings));
    originalSettings = JSON.parse(JSON.stringify(settings));
};

const navigateTo = (path) => {
    console.log(`导航到: ${path}`);
    if (path === '修改密码') {
        router.push('/settings/change-password');
    } else if (path === '隐私设置') {
         router.push('/settings/privacy');
    } else {
    ElMessage.info(`功能 '${path}' 待实现`);
    }
};

const logout = async () => {
    try {
        await userStore.logout();
    ElMessage.success('退出登录成功');
    router.push('/login');
    } catch (error) {
        ElMessage.error('退出登录失败');
        console.error('Logout failed:', error);
    }
};

const editAvatar = () => {
    ElMessage.info('修改头像功能待实现');
    // Implement avatar upload/selection logic here
    // e.g., open a dialog with ElUpload
};

// --- User Profile Functions ---
const saveUserProfile = async () => {
    // Basic validation (example)
    if (!editableUserInfo.username) {
        ElMessage.error('用户名不能为空');
        return;
    }
    // Check if data actually changed (optional but good practice)
    const changed = editableUserInfo.username !== userStore.user?.username ||
                    editableUserInfo.email !== userStore.user?.email ||
                    editableUserInfo.nickname !== userStore.user?.nickname;

    if (!changed) {
        ElMessage.info('用户信息未更改');
        return;
    }

    console.log('Saving user profile:', JSON.parse(JSON.stringify(editableUserInfo)));
    ElMessage.info('保存用户信息功能待实现 (API 调用)');

    // TODO: Implement API call to update user profile
    // try {
    //    const userId = userStore.user.id;
    //    const updatedUser = await apiService.users.updateUser(userId, editableUserInfo);
    //    userStore.setUser(updatedUser); // Update store with response from backend
    //    ElMessage.success('用户信息已更新');
    // } catch (error) {
    //    console.error('Failed to update user profile:', error);
    //    ElMessage.error('更新用户信息失败');
    // }
};

</script>

<style scoped>
.settings-view {

    height: 100vh;
    width: 100%;
    max-width: none;
    margin: 0;
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    color: #333;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* --- Dark Mode --- */
.dark-mode .settings-view {
    color: #ddd;
}
.dark-mode .settings-card {
    background-color: #2c2c2c;
    border-color: #444;
}
.dark-mode .view-title,
.dark-mode .card-title,
.dark-mode .item-label,
.dark-mode .item-value,
.dark-mode .logout-label,
.dark-mode .app-name,
.dark-mode .app-version,
.dark-mode .copyright,
.dark-mode .el-avatar,
.dark-mode .edit-avatar-btn {
    color: #eee;
}
.dark-mode .setting-item {
    border-bottom-color: #444;
}
.dark-mode .setting-item:hover {
    background-color: #383838;
}
.dark-mode .el-button {
    /* Optional: Adjust button styles for dark mode if needed */
}
.dark-mode .el-button--primary {
    /* Optional: Adjust primary button styles for dark mode if needed */
}
.dark-mode .el-input__inner,
.dark-mode .el-select .el-input__inner {
    background-color: #3a3a3a !important;
    border-color: #555 !important;
    color: #eee !important;
}
.dark-mode .el-select-dropdown {
    background-color: #2c2c2c;
    border-color: #444;
}
.dark-mode .el-select-dropdown__item {
    color: #ddd;
}
.dark-mode .el-select-dropdown__item.hover,
.dark-mode .el-select-dropdown__item:hover {
    background-color: #383838;
}
.dark-mode .el-switch.is-checked .el-switch__core {
    border-color: #409EFF;
    background-color: #409EFF;
}
.dark-mode .el-switch__core {
    background: #555;
    border-color: #555;
}
.dark-mode .about-card .copyright {
     color: #aaa;
}

/* --- General Layout --- */
.view-title {
    font-size: 50px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #1a1a1a;
}

.settings-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 24px;
    flex: 1;
    overflow: hidden;
    margin-bottom: 15px;
    grid-auto-rows: minmax(min-content, max-content);
}

.settings-card {
    background-color: #fff;
    border-radius: 16px;
    padding: 20px 24px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    border: 1px solid #e8e8e8;
    transition: box-shadow 0.3s ease;
    overflow-y: auto;
    height: 500px;
    max-height: 500px;
    display: flex;
    flex-direction: column;
}

.settings-card:hover {
     box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-title {
    font-size: 30px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #333;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 10px;
}

.settings-list {
    margin-top: 10px;
    flex-grow: 1;
    overflow-y: auto;
}

/* --- Setting Item Layout --- */
.setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    transition: background-color 0.2s ease;
    min-height: 46px;
}

.setting-item:last-child {
    border-bottom: none;
}

.setting-item.clickable {
    cursor: pointer;
}

.setting-item.clickable:hover {
    background-color: #f9f9f9;
}

.item-label {
    font-size: 18px;
    color: #444;
    margin-right: 15px;
    flex-shrink: 0;
}

.item-control {
    margin-left: auto;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.item-value {
    font-size: 20px;
    color: #666;
    text-align: right;
}

/* Ensure Element Plus components align well */
.item-control .el-select,
.item-control .el-input,
.item-control .el-switch {
    /* Add specific alignment/margin if needed, but align-items on parent helps */
}

/* Icons */
.arrow-icon, .logout-icon {
    color: #aaa;
    font-size: 16px;
    margin-left: 8px;
}

/* Specific Item Adjustments */
.logout-item {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    border-bottom: none;
}

.logout-label {
    color: #f56c6c;
    font-weight: 500;
}

.logout-icon {
    color: #f56c6c;
}

/* About Card */
.about-card {
    max-height: none;
    height: 85%;
}

.about-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding-top: 5px;
}

.app-icon-placeholder {
    width: 50px;
    height: 50px;
    background-color: #eee;
    border-radius: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    color: #aaa;
    margin-bottom: 10px;
}

.app-name {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 3px;
    color: #333;
}

.app-version {
    font-size: 13px;
    color: #888;
    margin-bottom: 10px;
}

.copyright {
    font-size: 12px;
    color: #aaa;
}

/* Action Buttons */
.settings-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 0;
    margin-bottom: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    position: relative;
    bottom: 80px;
}

.settings-actions .el-button {
    margin-left: 15px;
    min-width: 100px;
    font-size: 14px;
}

#user-info-card {
    grid-column: 1;
    grid-row: 1;
    display: flex;
    flex-direction: column;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 15px;
    padding-top: 5px;
}

.clickable-avatar {
    cursor: pointer;
    transition: opacity 0.2s ease;
}

.clickable-avatar:hover {
    opacity: 0.85;
}

/* Style for inline inputs */
.item-control .inline-input {
    --el-input-border-color: transparent;
    --el-input-hover-border-color: var(--el-border-color-hover);
    --el-input-focus-border-color: var(--el-color-primary);
    box-shadow: none !important;
    background-color: transparent;
    padding-left: 0;
    padding-right: 0;
    text-align: right;
}

.item-control .inline-input .el-input__wrapper {
    background-color: transparent !important;
    box-shadow: none !important;
    padding: 1px 0;
}

.item-control .inline-input.is-focus .el-input__wrapper {
    box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}

:deep(.inline-input .el-input__inner) {
    text-align: right;
    font-size: 18px;
}

.user-info-actions {
    margin-top: 15px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
}

.dark-mode .item-control .inline-input {
    --el-input-border-color: transparent;
    --el-input-hover-border-color: #555;
    --el-input-focus-border-color: #409EFF;
    color: #eee;
}
.dark-mode .item-control .inline-input .el-input__wrapper {
     background-color: transparent !important;
}
.dark-mode :deep(.inline-input .el-input__inner) {
    color: #eee;
    font-size: 18px;
}
.dark-mode .user-info-actions {
    border-top-color: #444;
}

.location-actions {
    margin-top: 10px;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.location-edit-btn {
    margin-left: 8px;
}

.dark-mode .location-actions {
    border-bottom-color: #444;
}
</style>